package net.csdn.business.facade;

import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.common.domain.request.CommentDeleteReqDto;
import net.csdn.business.common.domain.request.CommentSaveReqDto;
import net.csdn.business.common.domain.request.CommentUpdateReqDto;
import net.csdn.business.common.domain.vo.CommentVo;
import net.csdn.business.common.domain.vo.migrate.MigrateInfoLogVo;
import net.csdn.business.common.enums.UserTypeEnum;
import net.csdn.business.common.utils.JsonUtil;
import net.csdn.business.dto.CommentMigrateDto;
import net.csdn.business.enums.MigrateEnum;
import net.csdn.business.pojo.AtomGitIssueComment;
import net.csdn.business.pojo.AtomGitUser;
import net.csdn.business.util.MarkDownTansfer;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Component
public class CommentFacade {

    //private final CommentFeignClient commentFeignClient;
    private final UserFacade userFacade;
    private final MigrateFacade migrateFacade;

    @Value("${grpc.atomgit.issueDefaultConent:暂无内容}")
    private String issueDefaultConent;

    @Value("${grpc.atomgit.anonymous:65f906eb7af38bb6ff8XXX}")
    private String anonymous;


    public void saveComment(List<CommentMigrateDto> commentListList,
                            String repoId,String groupPath,String repoName,
                            String issueId,Long projectId){

        //String adminUid = userFacade.getAdminUserIdByProjectId(groupPath, repoName);
        String adminUid = anonymous;

        commentListList.forEach(comm->{
            try {
                MigrateInfoLogVo vo = migrateFacade.queryLog(MigrateEnum.MigrateInfoTypeEnum.COMMENT.code, String.valueOf(comm.getId()), groupPath, repoId);

                //查询用户
                AtomGitUser author = comm.getAuthor();
                String atomUserId = userFacade.queryForMigrateUser(author);
                if(StringUtils.isEmpty(atomUserId)){
                    atomUserId = adminUid;
                }
                if(ObjectUtils.isEmpty(vo.getId())){
                    //save
                    CommentVo save = saveCommnet(issueId, projectId, atomUserId, comm);
                    String commentId = save.getCommentId();
                    vo.setObjectId(commentId);
                    vo.setStatus(MigrateEnum.Status.SUCCESS.code);
                    migrateFacade.save(vo);
                }else{
                    // 查到原始评论
                    String objectId = vo.getObjectId();
                    CommentVo detail = null;
                    try {
                       // detail = commentFeignClient.getDetail(objectId);
                    } catch (Exception e) {
                        log.error("comment:{} has deleted",objectId);
                    }
                    if(ObjectUtils.isEmpty(detail)||!detail.getUid().equals(atomUserId) || vo.getStatus() == 0){
                        //需要重新插入评论数据
                        if(!ObjectUtils.isEmpty(detail) && (!detail.getUid().equals(atomUserId) || vo.getStatus() == 0)){
                            CommentDeleteReqDto commentDeleteReqDto = new CommentDeleteReqDto();
                            commentDeleteReqDto.setCommentId(objectId);
                            commentDeleteReqDto.setUid(detail.getUid());
                            //commentFeignClient.delete(commentDeleteReqDto);
                        }
                        //save comment
                        CommentVo save = saveCommnet(issueId, projectId, atomUserId, comm);
                        objectId = save.getCommentId();
                    }else{
                        // 正常更新
                        CommentUpdateReqDto commentUpdateReqDto = new CommentUpdateReqDto();
                        commentUpdateReqDto.setMigrateFlag(true);
                        commentUpdateReqDto.setCommentId(objectId);
                        if(StringUtils.isBlank(comm.getBody())){
                            commentUpdateReqDto.setContent(MarkDownTansfer.toHtml(issueDefaultConent));
                            commentUpdateReqDto.setMdContent(issueDefaultConent);
                        }else{
                            commentUpdateReqDto.setContent(MarkDownTansfer.toHtml(comm.getBody()));
                            commentUpdateReqDto.setMdContent(comm.getBody());
                        }
                        commentUpdateReqDto.setUid(detail.getUid());
                        commentUpdateReqDto.setUpdateDate(new Date(comm.getUpdatedAt()*1000));
                        //commentFeignClient.update(commentUpdateReqDto);
                    }

                    vo.setObjectId(objectId);
                    vo.setStatus(MigrateEnum.Status.SUCCESS.code);
                    migrateFacade.save(vo);
                }
            } catch (Exception e) {
                log.error("comm:{} save comment error:{}", JsonUtil.toJsonString(comm), JsonUtil.toJsonString(e));
            }
        });
    }

    private CommentVo saveCommnet(String issueId,Long projectId,String atomUserId,CommentMigrateDto comm){
        CommentSaveReqDto comment = new CommentSaveReqDto();
        comment.setMigrateFlag(true);
        comment.setIssueId(issueId);
        comment.setProjectId(projectId);
        comment.setReplyUser(atomUserId);
        comment.setCreateTime(new Date(comm.getCreatedAt()*1000));
        comment.setUpdateDate(new Date(comm.getUpdatedAt()*1000));


        if(StringUtils.isBlank(comm.getBody())){
            comment.setContent(MarkDownTansfer.toHtml(issueDefaultConent));
            comment.setMdContent(issueDefaultConent);

        }else{
            comment.setContent(MarkDownTansfer.toHtml(comm.getBody()));
            comment.setMdContent(comm.getBody());
        }

        comment.setUid(atomUserId);
        comment.setUserType(UserTypeEnum.USER.getType());
        //CommentVo save = commentFeignClient.save(comment);
        CommentVo save =null;
        return save;
    }


    /**
     * 评论 rebuild，针对有引用的评论，盖楼问题
     * 1，2，3，4，5
     * 1，12，23，34，45
     */

    public void saveCommentList(List<AtomGitIssueComment> commentList,String repoId,String groupPath,String repoName,
                                                        String issueId,Long projectId){
        if(CollectionUtils.isEmpty(commentList)){
            return;
        }
        Map<Long, List<AtomGitIssueComment>> commentGroup = commentList.stream().sorted(Comparator.comparing(AtomGitIssueComment::getCreatedAt))
                .collect(Collectors.groupingBy(AtomGitIssueComment::getInReplyToId));

        //默认分组 0 组 第一层级
        List<AtomGitIssueComment> comments = commentGroup.get(0L);
        comments.forEach(i-> {
            List<AtomGitIssueComment> list = Lists.newArrayList();
            list.add(i);
            List<AtomGitIssueComment> subComments = commentGroup.get(i.getId());
            if (CollectionUtils.isNotEmpty(subComments)) {
                list.addAll(subComments);
            }

            List<CommentMigrateDto> transformDtos = Lists.transform(list, ii -> {
                CommentMigrateDto commentMigrateDto = new CommentMigrateDto();
                commentMigrateDto.setId(ii.getId());
                commentMigrateDto.setBody(ii.getBody());
                commentMigrateDto.setAuthor(ii.getAuthor());
                commentMigrateDto.setCreatedAt(ii.getCreatedAt());
                commentMigrateDto.setUpdatedAt(ii.getUpdatedAt());
                commentMigrateDto.setInReplyToId(ii.getInReplyToId());
                return commentMigrateDto;
            });
            saveComment(transferMdContent(transformDtos),repoId,groupPath,repoName,issueId,projectId);
        });
    }


    public List<CommentMigrateDto> transferMdContent(List<CommentMigrateDto> transformDtos){
        transformDtos = new ArrayList<>(transformDtos);
        for(int i = transformDtos.size()-1;i>0;i--){
            CommentMigrateDto current = transformDtos.get(i);
            CommentMigrateDto frontSize = transformDtos.get(i-1);
            String referenceStr = convertToMarkdownQuote(frontSize.getBody()) + "\n\n";
            current.setBody(referenceStr + current.getBody());
            transformDtos.set(i,current);
        }
        return transformDtos;
    }
    public  String convertToMarkdownQuote(String input) {
        // 将字符串按行分割成数组
        String[] lines = input.split("\\r?\\n");

        // 构建 Markdown 引用字符串
        StringBuilder markdown = new StringBuilder();
        markdown.append("> "); // 添加引用符号

        // 将每一行添加到 Markdown 引用中
        for (String line : lines) {
            markdown.append(line); // 添加当前行
            markdown.append("\n"); // 添加换行符
            markdown.append("> "); // 添加引用符号
        }

        return markdown.toString();
    }

}
